package study.cell_game.objects;

import java.io.ObjectOutputStream.PutField;
import java.util.ArrayList;
import java.util.List;

import study.cell_game.enums.PlayerColor;
import study.cell_game.objects.tokens.Token;
import study.cell_game.scenes.GameScene;

public class Player {
	
	protected TokenDeck deck;
	protected List<Token> onboardTokens;
	protected Hand hand;
	
	public List<Cell> getAvailableCells(){
		CellMap map = GameScene.getInstance().getMap();// .getInstan
		List<Cell> result = new ArrayList<Cell>();
		List<Cell> startCells = map.getInitialCellsForPlayer1();
		for ( Cell cell : startCells){
			if(cell.getToken() == null){
				result.add(cell);
			}
		}
		
		for(Token token : onboardTokens){
			Cell tokenCell = token.getCell();
			for(Cell cell : tokenCell.getNeighbours()){
				if(cell != null && cell.getToken() == null){
					result.add(cell);
				}
			}
		}
		return result;
	}
	
	
	
	protected Player(PlayerColor color){
		this.deck = new TokenDeck(color);
		this.onboardTokens = new ArrayList<Token>();
		this.hand = new Hand(color);
		
		this.deck.shuffle();
	}
	
	private static Player instance;
	public static Player getInstance(){
		if(instance == null){
			instance = new Player(PlayerColor.BLUE);
		} 
		return instance;
	}
	
	public void placeToken(int tokenId){
		Token token = hand.getTokenByGlobalId(tokenId);
		onboardTokens.add(token);
		hand.deleteTokenFromHand(tokenId);
	}
	
	public void update(){
		int tokenDrawCount = 1;
		
		for(Token t : onboardTokens){
			t.update();
			tokenDrawCount += t.getTokenDraw();
		}
		
		if(tokenDrawCount > hand.emptySlotsCount()){
			tokenDrawCount = hand.emptySlotsCount();
		}
		
		//we move tokens from deck to hand
		for(int i=0; i<tokenDrawCount; i++){
			Token token = deck.take();
			if(token != null){
				hand.putTokenOnHand(token);
			}
		}
		
	}
	
	public void postUpdate(){
		for(Token t : onboardTokens){
			t.alignToMax();
		}
	}
	
	public Hand getHand()
	{
		return hand;
	}
	
	
	
}
